package your.packag;


import java.util.ArrayList;
import java.util.List;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;

import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;




import DAO.MyData;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;

import android.content.DialogInterface;
import android.content.Intent;


import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */

	String Url ="http://smartwebvina.com/smartlive/";
	TextView textuser;
	EditText edituser;
	TextView textpasswd;
	EditText editpasswd;
	Button login;
	String status;
	TextView register;
	List<Cookie> cookies;
	public static DefaultHttpClient postClient;
	public static HttpResponse response;
	ProgressDialog dialog;
    AlertDialog.Builder builder;
    static org.jsoup.nodes.Document doc;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textuser = (TextView)findViewById(R.id.textView1);
        textpasswd = (TextView)findViewById(R.id.textView2);
        edituser = (EditText)findViewById(R.id.editText1);
        editpasswd = (EditText)findViewById(R.id.editText2);
        login = (Button)findViewById(R.id.button1);
        register = (TextView)findViewById(R.id.link_to_register);
        
        textuser.setText("Username");
        textpasswd.setText("Password");
        login.setText("Login");
        register.setText("Register");
        
        edituser.setText("duyandroid");
        editpasswd.setText("123456");
        login.setOnClickListener(this);
        register.setOnClickListener(this);
        
        dialog = new ProgressDialog(this);
        builder = new AlertDialog.Builder(this);
        
//Note, you may get more than one cookie, therefore this list.

//Grab the name of your cookie.
//String cookieOne = cookies.get(0).getName();
//String value = cookies.get(0).getValue();
//String cookieOneDomain = cookies.get(0).getDomain();



//cookieManager.setCookie(cookieOneDomain, cookieOne);
//for (int i = 0; i < cookies.size(); i++) {
 //   Log.d("aaa", "- " + cookies.get(i));
//}
       	  

    }


    
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	dialog.dismiss();
               Intent intent;
                if(status.compareTo("My Money")==0)
        		{
        			
        			intent = new Intent(LoginActivity.this, MainActivity.class);
        		//bundle.putSerializable("http",(Serializable) postClient);    
        		//intent.putExtras(bundle);
        			
        			startActivity(intent);
        		}
        		else
        		{
        			
        			builder.setMessage("Username or password incorrect")
        			       .setCancelable(false)
        			       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        			           public void onClick(DialogInterface dialog, int id) {
        			               dialog.cancel();
        			           }
        			       });
        			AlertDialog alert = builder.create();
        			alert.show();
        		}

        }
};
    public void onClick(View v)
    {
    	

    	 
    	switch(v.getId())
    	{
    	
    	case R.id.button1: 
    		dialog = ProgressDialog.show(this, "", 
                    "Loading. Please wait...", true);

    		new Thread(new Runnable() {
  			  public void run() {
				cookies = sendPostData("http://smartwebvina.com/smartlive/index.php?option=com_user&view=login&return=aHR0cDovL3NtYXJ0d2VidmluYS5jb20vc21hcnRsaXZlLw==", edituser.getText().toString(), 
				    				editpasswd.getText().toString());
				handler.sendEmptyMessage(0);

  			  }
    		}).start();
    		

    		
    		break;
    	case R.id.link_to_register:
    		Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
    		startActivity(intent);
    		break;
    		
    	}
    }
    

	public List<Cookie> sendPostData(String url, String user, String pass) {

		// Setup a HTTP client, HttpPost (that contains data you wanna send) and
		   // a HttpResponse that gonna catch a response.
	
		   postClient = new DefaultHttpClient();
		   HttpPost httpPost = new HttpPost(url);
		  
		  // HttpResponse response;
		   List<Cookie> cookies = null;
		  
		  
		

		   try {   
			  
		      // Make a List. Increase the size as you wish.
		      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

		      // Add your form name and a text that belongs to the actual form.
		      
		      nameValuePairs.add(new BasicNameValuePair("username", user));
		      nameValuePairs.add(new BasicNameValuePair("passwd", pass));
		
		    //  nameValuePairs.add(new BasicNameValuePair("remember", "yes"));
		      
		      nameValuePairs.add(new BasicNameValuePair("option", "com_user"));
		      nameValuePairs.add(new BasicNameValuePair("task", "login"));
		      nameValuePairs.add(new  BasicNameValuePair("return", "aHR0cDovL3NtYXJ0d2VidmluYS5jb20vc21hcnRsaXZlLw=="));
		      nameValuePairs.add(new  BasicNameValuePair("f6f6cb580925b9a2a5f5d2e83482456e", "1"));

		      // Set the entity of your HttpPost.
		      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

		      // Execute your request against the given url and catch the response.
		      response = postClient.execute(httpPost);
		    
		      HttpEntity httpEntity =response.getEntity();
				String xml = EntityUtils.toString(httpEntity);
				 String temp = Jsoup.parse(xml).toString();
				 doc = Jsoup.parse(temp);
				MyData data = new MyData();
			   status = data.getLogin(doc);
		    		  
		      if(response.getStatusLine().getStatusCode() == 200) {
		         // Green light. Catch your cookies from your HTTP response.
		          cookies =  postClient.getCookieStore().getCookies(); 
		         return  cookies;
		      }
		   } 
		 //  catch (SAXException e) {
            //Log.e("Error: ", e.getMessage());
		  // }
		   catch (Exception e) {
			   
		   }
		   return  cookies;
	
	}
	
	@Override
	protected void onResume() {
	super.onResume();
	
		dialog.cancel();
	
	}
	


    
    
}